package com.hue.concurrent.day05;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 使用await、signal实现交替输出
 */
public class Demo06 {
    public static void main(String[] args) {
        AwaitSignal awaitSignal = new AwaitSignal();
        Condition condition1 = awaitSignal.newCondition();
        Condition condition2 = awaitSignal.newCondition();
        Condition condition3 = awaitSignal.newCondition();

        new Thread(() -> {
            awaitSignal.print("a", condition1, condition2);
        }).start();

        new Thread(() -> {
            awaitSignal.print("b", condition2, condition3);
        }).start();

        new Thread(() -> {
            awaitSignal.print("c", condition3, condition1);
        }).start();

        awaitSignal.lock();
        try {
            System.out.println("开始...");
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            awaitSignal.unlock();
        }
    }

    public static class AwaitSignal extends ReentrantLock {
        public void print(String str, Condition cur, Condition next) {
            while (true) {
                lock();
                try {
                    cur.await();
                    System.out.println(str);
                    Thread.sleep(1000);
                    next.signal();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    unlock();
                }
            }
        }
    }
}
